#!/usr/bin/env python
#
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

from controllers import ftclient
import csv

# TABLE = '551817'
# TABLE = '557519'
# TABLE = 568441
# TABLE = 569083
# TABLE = 571349
# TABLE = 571946 # 13/03/2011
# TABLE = 575528 # 14/03/2011
# TABLE = 581826 # 15/03/2011 - new format table from csvmerge.py
# TABLE = 598205 # 20/03/2011 - new format table from csvmerge.py
# TABLE = 603911 # 22/03/2011
# TABLE = 610069 # 24/03/2011
# TABLE = 613810 # 25/03/2011
# TABLE = 628316 # 29/03/2011
# TABLE = 655748 # 03/04/2011
#TABLE = 669093 # 07/04/2011
#TABLE = 669532 # 08/04/2011
# TABLE = 684430  # 11/04/2011
# TABLE = 688375 # 12/04/2011
# TABLE = 697461  # 14/04/2011
TABLE = 707645 # 15/04/2011

CAR_FORM_SOURCE = """<iframe src="https://spreadsheets.google.com/embeddedform?formkey=dEp2cmpVZHdIeUdBVWNIaTgtOUQzbEE6MQ" width="760" height="968" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>"""

HEAD = """<html><head>
<title>
Car Finder
</title>
<link type="text/css" rel="stylesheet" href="/static/style.css">
<script type="text/javascript" src="/static/script.js"></script>
</head>
<body>
"""
FOOT = """</body>
</html>
"""

CATEGORY_SORT_ORDER = { 'Resolved' : 0,
                        'Located' : 1,
                        'Located in Red Zone' : 2,
                        'Query' : 3,
                        'Not yet located' : 4 }

# don't forget to update the list in ../csvmerge.py if you update this.
REGO = 'Vehicle Rego'
CATEGORY = 'Category'
LOCATION = 'Pick up location'
APPROVED = 'Approved for pickup'
DAMAGE = 'Damage'

def categoryNum(r):
  return CATEGORY_SORT_ORDER.get(r.get(CATEGORY), 5)

def categoryOrder(r0, r1):
  return categoryNum(r0) - categoryNum(r1)

def queryInternal(queryString, rego):
  ft = ftclient.FTClient(None)
  out = ft.runGetQuery(queryString % (TABLE, REGO, rego))
  result = csv.reader(out.split('\n'))
  values = []
  headers = result.next()
  for r in result:
    record = dict(zip(headers, r))
    values.append(record)
  # resolve duplicate records problems:
  values.sort(cmp=categoryOrder)
  return values[0]

def queryTable(rego):
  result = queryInternal("select * from %s where '%s' = '%s' limit 10", rego)
  if result:
    return result
  else:
    # use 'contains ignoring case' due to inconsistencies in data from nzpd.
    # in some cases this may return unexpected data, particularly when multiple
    # regos match the query rego.  Use limit to prevent wild card queries from
    # killing us.
    return queryInternal(
      "select * from %s where '%s' contains ignoring case '%s' limit 10",
      rego)


class MainHandler(webapp.RequestHandler):
    def post(self):
        rego = self.request.get('rego')
        rego = rego.replace(' ', '').replace('-', '').upper()
        results = queryTable(rego)

        def printRow(key, value):
          self.response.out.write('<tr><th class="findcar">%s</th><td class="findcar">%s</td></tr>' % (key, value))

        self.response.out.write(HEAD)
        if results:
            self.response.out.write('<table>')
            # we might have matched some rego other than the supplied one.
            result_reg = results.get(REGO)
            printRow('Registration', result_reg)
            category = results.get(CATEGORY)
            # special verbiage for category 'Query'.
            if category == 'Query':
              category = 'We already have a query registered for this vehicle and you will be contacted in due course.'
            printRow(CATEGORY, category)
            # print location, even for for resolved vehicles.
            location = results.get(LOCATION)
            if not location:
              location = 'None'
            printRow(LOCATION, location)
            damage = results.get(DAMAGE)
            if damage == 'Extensive':
              printRow(DAMAGE, 
                       'Your vehicle has been located by police and '
                       'found to be extensively damaged. Please contact '
                       'your insurance company')
            self.response.out.write('</table>')
        else:
            self.response.out.write('<p>Car not found, please see the Vehicle Recovery Team at the Armagh St entrance to Hagley Park.</p>')
        self.response.out.write(FOOT)

def main():
    application = webapp.WSGIApplication([('/findcar', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
